package com.shangxian.giveithome.controller;

import com.shangxian.giveithome.result.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping("/utils")
public class UtilsController {

    @Autowired
    private WebApplicationContext applicationContext;

    @RequestMapping("/queryApi")
    public Result queryApi() {
        List<String> urls = new ArrayList<>();
        RequestMappingHandlerMapping requestMappingHandlerMapping =
                applicationContext.getBean(RequestMappingHandlerMapping.class);
        //获取Url与方法信息
        Map<RequestMappingInfo, HandlerMethod> handlerMethods =
                requestMappingHandlerMapping.getHandlerMethods();
        handlerMethods.forEach((requestMappingInfo, handlerMethod) -> {
            Set<String> patterns = requestMappingInfo.getPatternsCondition().getPatterns();
            patterns.forEach(url -> {
                if (!StringUtils.equals(url, "/error"))
                    urls.add(url + " " + requestMappingInfo.getName());
            });
        });
        return Result.success(urls);
    }
}
